<?php

class UserAction extends userbaseAction {

	
   public function ajaxlogin()
    {
       $username=$_POST['user_name'];
       $password=$_POST['password'];
       $f=$_POST['f'];
       
       $user=M('user');
	   if($f!='p')
		   $password = md5($password);
       $users= $user->where("username='".$username."' and password='".$password."'")->find();
        
       if(is_array($users))
       {
    	$data = array('status'=>1);
    	
       }else {
       	$data = array('status'=>0);
       }
		
    	echo json_encode($data);
    	exit;
    }
	
	public function getAccessToken($code){
		//$this->appid = 'wx5eedec751e461f29';
		//$this->appsecret = '8ec67e7a6b0fb05d59158f423c54f147';
		//$this->appid = 'wx374ae14f8da998ef';
		//$this->appsecret = '9d5f17e77b5c07e9202ffe21b83913a1';
		
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->appsecret&code=$code&grant_type=authorization_code";
		//$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
		$str = $this->http_request($url);
		$data = json_decode($str, true);
		
		
		if(isset($data['access_token'])){
			$ref = $this->getUserInfo($data['access_token'], $data['openid']);
			return $ref;
		}else{
			return false;
		}
	}

	public function getCode($c=0){
		//$this->appid = 'wx374ae14f8da998ef';
		//$this->appsecret = '9d5f17e77b5c07e9202ffe21b83913a1';
		$reuri = urlencode('http://qichemo.danshannet.com/wx/');
		$state = rand(1000, 9999).$c;
		$_SESSION['state'] = $state;
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->appid&redirect_uri=$reuri&response_type=code&scope=snsapi_userinfo&state=$state#wechat_redirect";
		header("location:$url");
	}
	
	public function getUserInfo($accesstoken, $openid){
		$url = "https://api.weixin.qq.com/sns/userinfo?access_token=$accesstoken&openid=$openid&lang=zh_CN";
		$str = $this->http_request($url);
		$data = json_decode($str, true);
		return $data;
	}

    /**
     * 用户登陆
     */
    public function login() {
        // var_dump($this->visitor);exit;
        // var_dump($_SESSION);exit;

        $this->visitor->is_login && $this->redirect('User/index');
        $openid = WechatAction::auth(WechatAction::$STATE_LOGIN);
        $_SESSION['current_openid']=$openid;

        if (IS_POST) {
            $username = $this->_post('username', 'trim');
            $password = $this->_post('password', 'trim');
            $remember = $this->_post('remember');
            if (empty($username)) {
                IS_AJAX && $this->ajaxReturn(0, L('please_input').L('password'));
                $this->error(L('please_input').L('username'));
            }
            if (empty($username)) {
                IS_AJAX && $this->ajaxReturn(0, L('please_input').L('password'));
                $this->error(L('please_input').L('password'));
            }
            //连接用户中心
            $passport = $this->_user_server();
            $uid = $passport->auth($username, $password);
            if (!$uid) {
                IS_AJAX && $this->ajaxReturn(0, $passport->get_error());
                $this->error($passport->get_error());
            }
            //登陆
            $this->visitor->login($uid, $remember);


            //完成微信绑定
            // D('Wechat')->where("openid='$openid'")->setField('user', $uid);

            //登陆完成钩子
            $tag_arg = array('uid'=>$uid, 'uname'=>$username, 'action'=>'login');
            tag('login_end', $tag_arg);
            //同步登陆
            $synlogin = $passport->synlogin($uid);
            if (IS_AJAX) {
                $this->ajaxReturn(1, L('login_successe').$synlogin);
            } else {
                //跳转到登陆前页面（执行同步操作）
                $ret_url = $this->_post('ret_url', 'trim');
                $this->success(L('login_successe').$synlogin, $ret_url);
            }
        } else {

            /* 同步退出外部系统 */
            $passport = $this->_user_server();
            if (!empty($_GET['synlogout'])) {
                $synlogout = $passport->synlogout();
            }

            // 检查是否绑定
            // $user = D('user')->findByOpenid($openid);
            // if($user) {
            //     $this->visitor->login($user['id'], 1);
            //     //登陆完成钩子
            //     $tag_arg = array('uid'=>$user['id'], 'uname'=>$user['username'], 'action'=>'login');
            //     tag('login_end', $tag_arg);
            //     //同步登陆
            //     $synlogin = $passport->synlogin($user['id']);

            //     $ret_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : __APP__;
            //     redirect($ret_url);
            // }


            if (IS_AJAX) {
                $resp = $this->fetch('dialog:login');
                $this->ajaxReturn(1, '', $resp);
            } else {
                //来路
                $ret_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : __APP__;
                $this->assign('ret_url', $ret_url);
//                $this->assign('synlogout', $synlogout);
//                $this->_config_seo();
                $this->display();
            }
        }
    }
    
    public function addaddress()
    {
    	if(IS_POST)
    	{
    	$user_address=M('user_address');
    	
    	$consignee= $this->_post('consignee', 'trim');
    	$sheng= $this->_post('sheng', 'trim');
    	$shi= $this->_post('shi', 'trim');
    	$qu= $this->_post('qu', 'trim');
    	$address= $this->_post('address', 'trim');
    	$phone_mob= $this->_post('phone_mob', 'trim');
    	
    	$data['uid']=$this->visitor->info['id'];
    	$data['consignee']=$consignee;
        $data['sheng']=$sheng;
    	$data['shi']=$shi;
    	$data['qu']=$qu;
    	$data['address']=$address;
    	$data['mobile']=$phone_mob;
    	
    	//echo $this->visitor->info['id'];
    	
        if($user_address->data($data)->add()!==false)
        {
       $this->redirect('User/address');
        }
     
    	}
    	$this->display();
    }

    /**
     * 用户退出
     */
    public function logout() {
        //取消绑定
        $uid = $this->visitor->info['id'];
        // D('user')->where("id=$uid")->setField('openid', '');

        //退出登录
        session('openid', null);
        $this->visitor->logout();
        //同步退出
        $passport = $this->_user_server();
        $synlogout = $passport->synlogout();
        //跳转到退出前页面（执行同步操作）
        $this->success(L('logout_successe').$synlogout, U('User/index'));
    }

    /**
     * 用户绑定
     */
    public function binding() {
        $user_bind_info = object_to_array(cookie('user_bind_info'));
        $this->assign('user_bind_info', $user_bind_info);
        $this->_config_seo();
        $this->display();
    }

    /**
    * 用户注册
    */
    public function register() {
        $this->visitor->is_login && $this->redirect('User/index');

        if (IS_POST) {

            $data = array(
                'username' => $this->_post('username', 'trim'),
                'openid' => $this->_post('openid', 'trim'),
            );

            $optional = array('truename', 'idcard', 'idcardimg', 'tel', 'bankaccount', 'bankname');
            foreach($optional as $f) {
                if(! empty($_POST[$f])) {
                    $data[$f] = $this->_post($f, 'trim');
                }
            }

            //确认信息是否全部填写
            if(count($data) == 8) {
                $data['is_identify'] = 1;
            }

            $data['usertype'] = 1;

            $Wechat = D('Wechat');
            $openid = $data['openid'];
            $wechat = $Wechat->where("openid='$openid'")->find();
            if($wechat) {
                $wechatInfo = json_decode($wechat['data']);
                $data['img'] = $wechatInfo->headimgurl;
                $data['gender'] = $wechatInfo->sex;
            } else {
                $data['gender'] = 1;
            }

            //用户禁止
            $ipban_mod = D('ipban');
            $ipban_mod->clear(); //清除过期数据
            $is_ban = $ipban_mod->where("(type='name' AND name='".$data['username']."')")->count();
  
            $is_ban && $this->error(L('register_ban'));
         
            //连接用户中心
            $passport = $this->_user_server();
            //注册
            $email = $data['username'] . '@eu-tmt.com';
//            $password = $this->_post('password', 'trim');
            $password = $this->_post('password', 'trim');
            $uid = $passport->register($data['username'], $password, $email, $data['gender']);

            //完成微信绑定
            $Wechat->where("openid='$openid'")->setField('user', $uid);

            !$uid && $this->error($passport->get_error());

            $yaoqingma = $this->_post('yaoqing', 'trim');

			if($yaoqingma == $_SESSION['yaoqing']){
				if($this->chkYqm($yaoqingma)){
					$sl = strrpos($yaoqingma, 'A');
					$el = strlen($yaoqingma) - $sl;
					$yqm = intval(substr($yaoqingma, $sl, $el), 10);
					$yqm_res = D('user')->where(array('id'=>$yqm))->find();
					if($yqm_res){
						$reg_data['pid'] = $yqm;
						
						$yj_data = array(
							'uid'=>$yqm,
							'count'=>C('pin_tuijian_jiangli'),
							'pid'=>$uid,
							'status'=>0,
							'addtime'=>time()
						);
						M('coupons')->add($yj_data);
					}
				}
			}

			$_SESSION['yaoqing'] = null;

            //保存注册数据
            $User = D('user');
            $User->where("id=$uid")->save($data);


            //注册完成钩子
            $username = $data['username'];
            $tag_arg = array('uid'=>$uid, 'uname'=> $username, 'action'=>'register');
            tag('register_end', $tag_arg);
            //登陆
            $this->visitor->login($uid);
            //登陆完成钩子
            $tag_arg = array('uid'=>$uid, 'uname'=>$username, 'action'=>'login');
            tag('login_end', $tag_arg);
            //同步登陆
            $synlogin = $passport->synlogin($uid);
            $this->redirect('User/index');
           // $this->success(L('register_successe').$synlogin, U('user/index'));
              
            exit;
        } else {
            //关闭注册
            if (!C('pin_reg_status')) {
                $this->error(C('pin_reg_closed_reason'));
            }

            $openid = WechatAction::auth(WechatAction::$STATE_REGISTER);
            //查询数据库中是否存在openid，存在登录
            $user = D('user')->findByOpenid($openid);;

            if($user){
                $this->error('您的微信账号已经绑定过账号，不可以重复绑定');
                redirect(U('login'));
            }

            $yaoqingma = $this->_get('user', 'trim', null);
			if(!$this->chkYqm($yaoqingma)) {
				$_SESSION['yaoqing'] = null;
			}else{
				$_SESSION['yaoqing'] = $yaoqingma;
			}

            $jsSign = $this->jsApiSign();
            $this->assign('js',$jsSign);

			$this->assign('yaoqing', $_SESSION['yaoqing']);
            $this->assign('openid', $openid);
            $this->_config_seo();
            $this->display();
        }
    }

	private function chkYqm($str){
		$ref = false;
		if(strlen($str)==12){
			if(substr($str, 0, 2)=='LR'){
				$tmp = intval(substr($str, 2), 10);
				if(is_int($tmp) && $tmp>0){
					$ref = true;
				}
			}
		}
		return $ref;
	}
    /**
     * 第三方头像保存
     */
    private function _save_avatar($uid, $img) {
        //获取后台头像规格设置
        $avatar_size = explode(',', C('pin_avatar_size'));
        //会员头像保存文件夹
        $avatar_dir = C('pin_attach_path') . 'avatar/' . avatar_dir($uid);
        !is_dir($avatar_dir) && mkdir($avatar_dir,0777,true);
        //生成缩略图
        $img = C('pin_attach_path') . 'avatar/temp/' . $img;
        foreach ($avatar_size as $size) {
            Image::thumb($img, $avatar_dir.md5($uid).'_'.$size.'.jpg', '', $size, $size, true);
        }
        @unlink($img);
    }
    
    /**
     * 用户消息提示 
     */
    public function msgtip() {
        $result = D('user_msgtip')->get_list($this->visitor->info['id']);
        $this->ajaxReturn(1, '', $result);
    }

	/**
	* 奖励收入
	*/
	public function shouru() {
		$jl_log=M('jiangli_log');
		if($_POST) {
			
		}
		$list = $jl_log->where('uid='.$this->visitor->info['id'])->select();
		foreach($list as $key=>$v){
			switch($v['status']){
				case '1':$s="审核中";$stime=$v['s1time'];break;
				case '2':$s="已结算";$stime=$v['s2time'];break;
				default:$s="已提交";$stime=$v['s0time'];
			}
			$list[$key]['status'] = $s;
			//$list[$key]['optime'] = date('Y-m-d H:i:s',$stime);
			$list[$key]['optime'] = date('y-m-d',$stime);
		}
		$this->assign('list',$list);
        $this->_config_seo();
        $this->display();
		
	}

	/**
	* 邀请加入
	*/
	public function yaoqing() {
		$user=M('user');
		$uid = $this->visitor->info['id'];

        $userinfo = $user->where('id='.$uid)->find();
		if($userinfo){
			$uid = $userinfo['id'];
			$yaoqing_img = trim($userinfo['yaoqing']);
			$yaoqing_str = trim($userinfo['yaoqingma']);

			if(!$yaoqing_img || !yaoqing_str){
                $yqm = 'LR'.getSj(1).'A'.$uid;
				$img = $this->png($yqm);
				$data = array(
					'yaoqing'=>$img,
					'yaoqingma'=>$yqm
				);
				$user->where('id='.$uid)->save($data);
				$userinfo['yaoqing'] = $img;
				$userinfo['yaoqingma'] = $yqm;
			}else{
				$yqm = $yaoqing_str;
			}
		}
		
		$jsSign = $this->jsApiSign();
        $this->assign('js',$jsSign);

        $this->assign('yaoqingma', $userinfo['yaoqingma']);
        $this->assign('userinfo',$userinfo);
        $this->assign('link', U('register', array('user' => $userinfo['yaoqingma']), false, false, true) );
        $this->assign('img', '/static/images/img03.png');

        $this->_config_seo();

        //分享配置
        $config = M('config')->where('name="share"')->find();
        if($config) {
            $this->assign('description', $config['content']);
        }

        $this->display();
	}

    public function qr($text) {
        vendor("phpqrcode.phpqrcode");
        $url="http://".$_SERVER['SERVER_NAME']."/index.php?m=User&a=register&user=".$text;
        QRcode::png($url, false, 'L', 4);
    }

	public function png($text) {
		vendor("phpqrcode.phpqrcode");
		$url="http://".$_SERVER['SERVER_NAME']."/index.php?m=User&a=register&user=".$text;
		$path = dirname(__FILE__);
		$path = str_replace("app\Lib\Action\home", "", $path);
		$path = str_replace("app/Lib/Action/home", "", $path);
		$filepath = "/erweima/".time().".png";
		QRcode::png($url, $path.$filepath, 'L', 4);
		return $filepath;
	}
	
	/**
	* 订单列表
	*/
	public function order() {
		$item_order=M('item_orders');
		$uid = $this->visitor->info['id'];
		$wh = array('uid'=>$uid, 'type'=>0);
		
		$item_orders= $item_order->order('id desc')->where($wh)->select();
		foreach($item_orders as $key=>$v){
			switch($v['status']){
				case '0':
					$sta = '未付款';
					break;
				case '1':
					$sta = '待发货';
					break;
				case '2':
					$sta = '已发货';
					break;
                case '4':
                    $sta = '已完成';
                    break;
				default:
					$sta = '已完成';
			}
			$item_orders[$key]['stat'] = $sta;
		}
		$this->assign('item_orders',$item_orders);	//用户信息
        $this->_config_seo();
        $this->display();
		
	}
	/**
	* 购物车列表
	*/
	public function cars() {
		$item_order=M('item_orders');
		$uid = $this->visitor->info['id'];
		$wh = array('uid'=>$uid, 'type'=>1);
		
		$item_orders= $item_order->order('id desc')->where($wh)->select();
		foreach($item_orders as $key=>$v){
			switch($v['status']){
				case '0':
					$sta = '未付款';
					break;
				case '1':
					$sta = '待发货';
					break;
				case '2':
					$sta = '已发货';
					break;
				default:
					$sta = '已完成';
			}
			$item_orders[$key]['status'] = $sta;
		}
		$this->assign('item_orders',$item_orders);	//用户信息
        $this->_config_seo();
        $this->display();
		
	}
	/**
	* 收藏列表
	*/
	public function coll() {
		$collection=M('collection');
		$uid = $this->visitor->info['id'];
		$wh = array('uid'=>$uid);
		
		$item_collection= $collection->order('id desc')->where($wh)->select();
		foreach($item_collection as $key=>$v){
			$item_collection[$key]['time'] = date('y-m-d H:i:s', $v['time']);
		}
		
		$this->assign('item_collection',$item_collection);	//用户信息
        $this->_config_seo();
        $this->display();
	}
	
	public function coll_del(){
		$ref = array(
			'status' => 0,
			'msg' => '未知错误'
		);
		if($_POST){
			$id = $this->_post('id', 'intval');
			if($id){
				$collection=M('collection');
				$uid = $this->visitor->info['id'];

                $where = array(
                    'uid' => $uid,
                    'id' => $id
                );

                $res = $collection->where($where)->delete();
				if($res){
                    $ref['status'] = 1;
                    $ref['msg'] = '删除成功';
				}else{
					$ref['msg'] = '删除失败';
				}
			}else{
				$ref['msg'] = '请确认您提交的数据合法';
			}
		}else{
			$ref['msg'] = '请使用正确的方式提交数据';
		}
		echo json_encode($ref);
		exit;
	}
	
	public function cars_del(){
		$ref = array(
			'status' => 0,
			'msg' => '未知错误'
		);
		if($_POST){
			$id = $this->_post('id', 'intval');
			if($id){
				$item_order=M('item_orders');
				$uid = $this->visitor->info['id'];
				$wh = array('uid'=>$uid, 'type'=>1, 'id'=>$id);

				$res = $item_order->where($wh)->delete();
                if($res){
                    $ref['status'] = 1;
                    $ref['msg'] = '删除成功';
                }else{
                    $ref['msg'] = '删除失败';
                }
			}else{
				$ref['msg'] = '请确认您提交的数据合法';
			}
		}else{
			$ref['msg'] = '请使用正确的方式提交数据';
		}
		echo json_encode($ref);
		exit;
	}
	
	/**
	* 修改注册信息
	*/
	public function mod() {
		$user=D('user');
		if($_POST) {
			$uid = $this->visitor->info['id'];
            $data = array(
                "truename" => $this->_post('truename', 'trim'),
                "idcard" => $this->_post('idcard', 'trim'),
                // "idcardimg" => $this->_post('idcardimg', 'trim'),
                "tel" => $this->_post('tel', 'trim'),
                // "bankaccount" => $this->_post('bankaccount', 'trim'),
                // "bankname" => $this->_post('bankname', 'trim'),
                "id" => $uid,
                "is_identify" => 1,
            );

            // $idcardimg = $this->_post('idcardimg', 'trim');
            // $changed = $this->_post('idcardimg_changed', 'trim');
            // if($idcardimg && $changed) {
            //     $data['idcardimg'] = $this->saveWechatImg($idcardimg);
            // }

            $result = $user->data($data)->save();

			exit;
		}else{
			$uinfo = $user->where('id='.$this->visitor->info['id'])->find();
			$this->assign('userinfo',$uinfo);	//用户信息

            $this->assign('js', $this->jsApiSign());

			$this->_config_seo();
			$this->display();
		}
	}
	
	
	/**
	* 修改头像
	*/
	public function modheadimg() {
		$user=M('user');
		if($_POST) {
			$uid = $this->visitor->info['id'];
			$img = $this->_post('img', 'trim');
			
			$mod_data = array();
			
			if($img!=null)
				$mod_data['img'] = $img;
			
			if($mod_data){
				$res= $user->where(array('id'=>$uid))->save($mod_data);
			}else{
				$res = 1;
			}
			
			$ref = array();
			if($res == 1){
				$ref['status']=1;
			}else{
				$ref['status']=0;
			}
			echo json_encode($ref);
			exit;
		}
	}
    /**
    * 基本信息修改
    */
    public function index() {
      $user=M('user');
      $item_order=M('item_orders');
      $order_detail=M('order_detail');
	  $collection = M('collection');
	  
	  $uid = $this->visitor->info['id'];
	  $wh = array(
		'status'=>array('lt',4), 
		'uid'=>$uid,
		'type'=>0
	  );
	  
	  $wh_car = array(
		'uid'=>$uid,
		'type'=>1
	  );
	  
	  $wh_col = array(
		'uid' => $uid
	  );
	  
	  $item_collection = $collection->order('id DESC')->where($wh_col)->limit('0, 3')->select();
      $item_car= $item_order->order('id desc')->where($wh_car)->limit('0,3')->select();
      $item_orders= $item_order->order('id desc')->where($wh)->limit('0,3')->select();

	  $uinfo = $user->where('id='.$uid)->select();
	  if(count($uinfo)==1){
		  $userinfo = $uinfo[0];
		  $jiangli_db = $this->getCurJiangLi($uid);
          $rebate = number_format($jiangli_db, 2);
          $this->assign('rebate', explode('.', $rebate) );
	  }
	  
       $this->assign('item_collection',$item_collection);
       $this->assign('item_orders',$item_orders);
       $this->assign('item_car',$item_car);
//       $this->assign('status',$status);
       $this->assign('usertype',$userinfo['usertype']=='汽车膜'?'1':'2');	//用户信息
       $this->assign('userinfo',$userinfo);	//用户信息
        $this->_config_seo();

        //微信签名
        $this->assign('js',$this->jsApiSign());

        $this->display();
//        dump($item_orders);exit;
    }
	
	
	public function forgetpass(){
		if($_POST){
			$ref = array('status'=>0, 'msg'=>'未知错误');
			$truename=$this->_post('truename', 'trim');
			$idcard=$this->_post('idcard', 'trim');
			$pass0=$this->_post('password', 'trim');
			
			//判断格式
			$where = array(
				'truename'=>$truename,
				'idcard'=>$idcard
			);
			
			$data = array(
				'password'=>md5($pass0),
				'updatetime'=>time()
			);
			
			$res = D('user')->where($where)->find();
			if($res){
				$res_up = D('user')->where($where)->save($data);
				if($res_up){
					$ref['status'] = 1;
					$ref['msg'] = '重置密码成功';
				}else{
					$ref['msg'] = '重置密码失败';
				}
			}else{
				$ref['msg'] = '请确认提供的真实姓名和身份证是合法的';
			}
			
			echo json_encode($ref);
			exit;
		}else{
			$this->display();
		}
	}
	
	private function getCurJiangLi($uid){
        $Order = new OrderModel();
        $rebate = $Order->getUserRebateMonth($uid);
        return $rebate[1]['award'] + $rebate[2]['award'];
	}
	
	private function jisuan($uid, $s_t, $e_t, $cate){
		$utype = M('usertype');
		$order = M('item_orders');
		$where = array(
			'uid' => $uid,
			'status' => 4,
			'type' => 1,
			'cate' => array('like', "$cate%"),
			'done_time' => array('between', "$s_t, $e_t")
		);
		$o_result = $order->where($where)->field('sum(`count`) as c, count(id) as cc')->find();
		if($o_result){
			$utwhere = array(
				'type' => array('like', "$cate%"),
				'tiaojian0' => array('elt', $o_result['cc']),
				'tiaojian1' => array('egt', $o_result['cc'])
			);
			$u_list = $utype->where($utwhere)->find();
			if($u_list){
				$count = ($o_result['c'] * $u_list['bili']) / 100;
			}else{
				$count = 0;
			}
		}
		return $count;
	}
	
	
	public function modusertype(){
		$ref = array('status'=>0);
		$t = $this->_post('t', 'trim');
		if($t=='汽车膜'||$t=='建筑膜'){
			$data = array('usertype'=>$t);
			$where = array('id'=>$this->visitor->info['id']);
			$res = M('user')->where($where)->save($data);
			if(res){
				$ref['status'] = 1;
			}
		}
		echo json_encode($ref);
		exit;
	}

    /**
     * 修改头像
     */
    public function upload_avatar() {

        if (!empty($_FILES['avatar']['name'])) {
            //会员头像规格
            $avatar_size = explode(',', C('pin_avatar_size'));
            //回去会员头像保存文件夹
            $uid = abs(intval($this->visitor->info['id']));
            $suid = sprintf("%09d", $uid);
            $dir1 = substr($suid, 0, 3);
            $dir2 = substr($suid, 3, 2);
            $dir3 = substr($suid, 5, 2);
            $avatar_dir = $dir1.'/'.$dir2.'/'.$dir3.'/';
            //上传头像
            $suffix = '';
            foreach ($avatar_size as $size) {
                $suffix .= '_'.$size.',';
            }
            $result = $this->_upload($_FILES['avatar'], 'avatar/'.$avatar_dir, array(
                'width'=>C('pin_avatar_size'), 
                'height'=>C('pin_avatar_size'),
                'remove_origin'=>true, 
                'suffix'=>trim($suffix, ','),
                'ext' => 'jpg',
            ), md5($uid));
            if ($result['error']) {
                $this->ajaxReturn(0, $result['info']);
            } else {
                $data = __ROOT__.'/data/upload/avatar/'.$avatar_dir.md5($uid).'_'.$size.'.jpg?'.time();
                $this->ajaxReturn(1, L('upload_success'), $data);
            }
        } else {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
    }

    /**
     * 修改密码
     */
    public function password() {
        if( IS_POST ){
            $oldpassword = $this->_post('oldpassword','trim');
            $password   = $this->_post('password','trim');
            $repassword = $this->_post('repassword','trim');
            !$password && $this->error(L('no_new_password'));
            $password != $repassword && $this->error(L('inconsistent_password'));
            $passlen = strlen($password);
            if ($passlen < 6 || $passlen > 20) {
                $this->error('password_length_error');
            }
            //连接用户中心
            $passport = $this->_user_server();
            $result = $passport->edit($this->visitor->info['id'], $oldpassword, array('password'=>$password));
            if ($result) {
                $msg = array('status'=>1, 'info'=>L('edit_password_success'));
            } else {
                $msg = array('status'=>0, 'info'=>$passport->get_error());
            }
            $this->assign('msg', $msg);
        }
        $this->_config_seo();
        $this->display();
    }

    /**
     * 帐号绑定
     */
    public function bind() {
        //获取已经绑定列表
        $bind_list = M('user_bind')->field('type')->where(array('uid'=>$this->visitor->info['id']))->select();
        $binds = array();
        if ($bind_list) {
            foreach ($bind_list as $val) {
                $binds[] = $val['type'];
            }
        }
        
        //获取网站支持列表
        $oauth_list = $this->oauth_list;
        foreach ($oauth_list as $type => $_oauth) {
            $oauth_list[$type]['isbind'] = '0';
            if (in_array($type, $binds)) {
                $oauth_list[$type]['isbind'] = '1';
            }
        }
        $this->assign('oauth_list', $oauth_list);
        $this->_config_seo();
        $this->display();
    }

    /**
     * 个人空间banner背景设置
     */
    public function custom() {
        $cover = $this->visitor->get('cover');
        $this->assign('cover', $cover);
        $this->_config_seo();
        $this->display();
    }

    /**
     * 取消封面
     */
    public function cancle_cover() {
        $result = M('user')->where(array('id'=>$this->visitor->info['id']))->setField('cover', '');
        !$result && $this->ajaxReturn(0, L('illegal_parameters'));
        $this->ajaxReturn(1, L('edit_success'));
    }

    /**
     * 上传封面图片
     */
    public function upload_cover() {
        if (!empty($_FILES['cover']['name'])) {
            $data_dir = date('ym/d');
            $file_name = md5($this->visitor->info['id']);
            $result = $this->_upload($_FILES['cover'], 'cover/'.$data_dir, array('width'=>'900', 'height'=>'330', 'remove_origin'=>true), $file_name);
            if ($result['error']) {
                $this->ajaxReturn(0, $result['info']);
            } else {
                $ext = array_pop(explode('.', $result['info'][0]['savename']));
                $cover = $data_dir.'/'.$file_name.'_thumb.'.$ext;
                $data = '<img src="./data/upload/cover/'.$data_dir.'/'.$file_name.'_thumb.'.$ext.'?'.time().'">';
                //更新数据
                M('user')->where(array('id'=>$this->visitor->info['id']))->setField('cover', $cover);
                $this->ajaxReturn(1, L('upload_success'), $data);
            }
        } else {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
    }

    
    public function edit_address()
    {
       $user_address_mod = M('user_address');
        $id = $this->_get('id', 'intval');
        $info = $user_address_mod->find($id);
       
       $this->assign('info', $info);
    	$this->display();
    }
    
    /**
     * 收货地址
     */
    public function address() {
        $user_address_mod = M('user_address');
        $id = $this->_get('id', 'intval');
        $type = $this->_get('type', 'trim', 'edit');
        if ($id) {
            if ($type == 'del') {
                $user_address_mod->where(array('id'=>$id, 'uid'=>$this->visitor->info['id']))->delete();
                $msg = array('status'=>1, 'info'=>L('delete_success'));
                $this->assign('msg', $msg);
            } else {
                $info = $user_address_mod->find($id);
                $this->assign('info', $info);
            }
        }
        if (IS_POST) {
            $consignee = $this->_post('consignee', 'trim');
            $address = $this->_post('address', 'trim');
         //   $zip = $this->_post('zip', 'trim');
         $mobile = $this->_post('phone_mob', 'trim');
         $sheng = $this->_post('sheng', 'trim');
         $shi = $this->_post('shi', 'trim');
         $qu = $this->_post('qu', 'trim');
            $id = $this->_post('id', 'intval');
            if ($id) {
                $result = $user_address_mod->where(array('id'=>$id, 'uid'=>$this->visitor->info['id']))->save(array(
                    'consignee' => $consignee,
                    'address' => $address,
                   // 'zip' => $zip,
                    'mobile' => $mobile,
                     'sheng' => $sheng,
                      'shi' => $shi,
                       'qu' => $qu,
                ));
                if ($result) {
                    $msg = array('status'=>1, 'info'=>L('edit_success'));
                } else {
                    $msg = array('status'=>0, 'info'=>L('edit_failed'));
                }
            } else {
                $result = $user_address_mod->add(array(
                    'uid' => $this->visitor->info['id'],
                    'consignee' => $consignee,
                    'address' => $address,
//                    'zip' => $zip,
                    'mobile' => $mobile,
                ));
                if ($result) {
                    $msg = array('status'=>1, 'info'=>L('add_address_success'));
                } else {
                    $msg = array('status'=>0, 'info'=>L('add_address_failed'));
                }
            }
            $this->assign('msg', $msg);
        }
        
        $address_list = $user_address_mod->where(array('uid'=>$this->visitor->info['id']))->select();
        $this->assign('address_list', $address_list);
        $this->_config_seo();
        $this->display();
    }
   
    /**
     * 检测用户
     */
    public function ajax_check() {
        $type = $this->_get('type', 'trim', 'email');
        $user_mod = D('user');
        switch ($type) {
            case 'email':
                $email = $this->_get('J_email', 'trim');
                $user_mod->email_exists($email) ? $this->ajaxReturn(0) : $this->ajaxReturn(1);
                break;
            
            case 'username':
                $username = $this->_get('J_username', 'trim');
                $user_mod->name_exists($username) ? $this->ajaxReturn(0) : $this->ajaxReturn(1);
                break;
        }
    }

    /**
     * 关注
     */
    public function follow() {
        $uid = $this->_get('uid', 'intval');
        !$uid && $this->ajaxReturn(0, L('follow_invalid_user'));
        $uid == $this->visitor->info['id'] && $this->ajaxReturn(0, L('follow_self_not_allow'));
        $user_mod = M('user');
        if (!$user_mod->where(array('id'=>$uid))->count('id')) {
            $this->ajaxReturn(0, L('follow_invalid_user'));
        }
        $user_follow_mod = M('user_follow');
        //已经关注？
        $is_follow = $user_follow_mod->where(array('uid'=>$this->visitor->info['id'], 'follow_uid'=>$uid))->count();
        $is_follow && $this->ajaxReturn(0, L('user_is_followed'));
        //关注动作
        $return = 1;
        //他是否已经关注我
        $map = array('uid'=>$uid, 'follow_uid'=>$this->visitor->info['id']);
        $isfollow_me = $user_follow_mod->where($map)->count();
        $data = array('uid'=>$this->visitor->info['id'], 'follow_uid'=>$uid, 'add_time'=>time());
        if ($isfollow_me) {
            $data['mutually'] = 1; //互相关注
            $user_follow_mod->where($map)->setField('mutually', 1); //更新他关注我的记录为互相关注
            $return = 2;
        }
        $result = $user_follow_mod->add($data);
        !$result && $this->ajaxReturn(0, L('follow_user_failed'));
        //增加我的关注人数
        $user_mod->where(array('id'=>$this->visitor->info['id']))->setInc('follows');
        //增加Ta的粉丝人数
        $user_mod->where(array('id'=>$uid))->setInc('fans');
        //提醒被关注的人
        D('user_msgtip')->add_tip($uid, 1);
        //把他的微薄推送给我
        //TODO...是否有必要？
        $this->ajaxReturn(1, L('follow_user_success'), $return);
    }

    /**
     * 取消关注
     */
    public function unfollow() {
        $uid = $this->_get('uid', 'intval');
        !$uid && $this->ajaxReturn(0, L('unfollow_invalid_user'));
        $user_follow_mod = M('user_follow');
        if ($user_follow_mod->where(array('uid'=>$this->visitor->info['id'], 'follow_uid'=>$uid))->delete()) {
            $user_mod = M('user');
            //他是否已经关注我
            $map = array('uid'=>$uid, 'follow_uid'=>$this->visitor->info['id']);
            $isfollow_me = $user_follow_mod->where($map)->count();
            if ($isfollow_me) {
                $user_follow_mod->where($map)->setField('mutually', 0); //更新他关注我的记录为互相关注
            }
            //减少我的关注人数
            $user_mod->where(array('id'=>$this->visitor->info['id']))->setDec('follows');
            //减少Ta的粉丝人数
            $user_mod->where(array('id'=>$uid))->setDec('fans');
            //删除我微薄中Ta的内容
            M('topic_index')->where(array('author_id'=>$uid, 'uid'=>$this->visitor->info['id']))->delete();
            $this->ajaxReturn(1, L('unfollow_user_success'));
        } else {
            $this->ajaxReturn(0, L('unfollow_user_failed'));
        }
    }

    /**
     * 保存头像
     * @param $mediaId
     */
    public function headimg($mediaId) {
        if(empty($mediaId)) {
            $this->error('缺少媒体文件');
        }

        $path = $this->saveWechatImg($mediaId);
        D('user')->where("id=" . $this->visitor->info['id'])->save(array('img' => $path));
        $this->success('ok');
    }

    /**
     * 移除粉丝
     */
    public function delfans() {
        $uid = $this->_get('uid', 'intval');
        !$uid && $this->ajaxReturn(0, L('delete_invalid_fans'));
        $user_follow_mod = M('user_follow');
        if ($user_follow_mod->where(array('follow_uid'=>$this->visitor->info['id'], 'uid'=>$uid))->delete()) {
            $user_mod = M('user');
            //减少我的粉丝人数
            $user_mod->where(array('id'=>$this->visitor->info['id']))->setDec('fans');
            //减少Ta的关注人数
            M('user')->where(array('id'=>$uid))->setDec('follows');
            //删除Ta微薄中我的内容
            M('topic_index')->where(array('author_id'=>$this->visitor->info['id'], 'uid'=>$uid))->delete();
            $this->ajaxReturn(1, L('delete_fans_success'));
        } else {
            $this->ajaxReturn(0, L('delete_fans_failed'));
        }
    }

    private function saveWechatImg($mediaId) {
        $token = $this->getGlobelAccessToken();
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$token&media_id=" . $mediaId;
        //下载
        $response = $this->http_request($url, null, 'get', true);
        //保存
        $upload_path= 'data/upload/wechat/' . $mediaId;
        if(!empty($response['headers']['Content-disposition']) ) {
            $cd = $response['headers']['Content-disposition'];
            $matchs = array();
            $nr = preg_match('/filename="(.+)"$/', $cd, $matchs);
            if($nr > 0) {
                $upload_path= 'data/upload/wechat/' . $matchs[1];
            }
        }

        $size = file_put_contents($upload_path, $response['content']);
        unset($content);

        return __ROOT__ . $upload_path;
    }
}
